package com.example.weatherreport;

import static android.content.Context.MODE_PRIVATE;

import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.weatherreport.base.BaseFragment;
import com.example.weatherreport.bean.WeatherBean;
import com.example.weatherreport.db.DBManager;
import com.example.weatherreport.location.NowCityUtil;
import com.example.weatherreport.utils.SpUtils;
import com.example.weatherreport.utils.TimeUtils;
import com.example.weatherreport.utils.WeekdayConverter;
import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;


public class CityWeatherFragment extends BaseFragment implements View.OnClickListener {
    TextView tempTv, frag_tv_PM2_5, frag_tv_sunrise, frag_tv_sunset, frag_tv_aqi_name, conditionTv, windTv, tempRangeTv, dateTv, clothIndexTv, carIndexTv, coldIndexTv, sportIndexTv, raysIndexTv, tipTv, umbrellaTv;
    ImageView weather_icon;
    String url1 = "https://wis.qq.com/weather/common?source=pc&weather_type=observe|index|rise|alarm|air|tips|forecast_24h&province=";
    String url2 = "&city=";
    String city;
    String provice;
    LinearLayout futureLayout;
    ScrollView outLayout;
    public static WeatherBean.DataBean.IndexBean index;
    public static String MSG;

    // 交换背景图片
    private SharedPreferences pref;
    private int bgNum;

    public CityWeatherFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_city_weather, container, false);
        initView(view);
        exchangeBg();//打开页面交换壁纸
        //可以通过activity传值获取到当前fragment加载的是那个地方的省份和天气情况
        Bundle bundle = getArguments();
        String provice_city = bundle.getString("city");
        //获取省份
        if (provice_city.split(" ").length > 1) {
            provice = provice_city.split(" ")[0];
            city = provice_city.split(" ")[1];
        } else {
            city = provice_city.split(" ")[0];
            provice = provice_city.split(" ")[0];
        }
        String url = url1 + provice + url2 + city;
        //调用父类获取数据的方法
        loadData(url);
        return view;
    }

    @Override
    public void onSuccess(String result) {
        // 解析并展示数据
        try {
            parseShowData(result);
        } catch (ParseException | NoSuchMethodException | IllegalAccessException |
                 InvocationTargetException e) {
            e.printStackTrace();
        }
        // 更新数据
        int i = DBManager.updateInfoByCity(city, result);
        if (i <= 0) {
            // 更新数据库失败，说明没有这条城市信息，增加这个城市记录
            DBManager.addCityInfo(city, result);

            List<String> strings = DBManager.queryAllCityName();
        }
    }


    private void parseShowData(String result) throws ParseException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 使用gson解析数据
        WeatherBean weatherBean = new Gson().fromJson(result, WeatherBean.class);
        WeatherBean.DataBean resultsBean = weatherBean.getData();
//        System.out.println("result"+resultsBean.toString());

        index = resultsBean.getIndex();
        /**
         * 设置基础天气数据
         */
        // 设置TextView

//        System.out.println("index"+index.toString());
        WeatherBean.DataBean.AirBean air = resultsBean.getAir();
//        设置TextView
        System.out.println("test:  " + air);
        frag_tv_aqi_name.setText("空气质量 " + air.getAqi_name());
        frag_tv_PM2_5.setText("PM2.5 " + air.getPm2_5());

        Drawable drawable = getResources().getDrawable(R.mipmap.sunrise);
        drawable.setBounds(0, 0, 50, 50); // 设置图标的宽高
        frag_tv_sunrise.setCompoundDrawables(null, null, drawable, null); // 设置drawableLeft
        frag_tv_sunrise.setText("" + resultsBean.getRise().get_$0().getSunrise());

        Drawable drawable2 = getResources().getDrawable(R.mipmap.sunset);
        drawable2.setBounds(0, 0, 50, 50); // 设置图标的宽高


        frag_tv_sunset.setCompoundDrawables(null, null, drawable2, null);
        frag_tv_sunset.setText("" + resultsBean.getRise().get_$0().getSunset());
        frag_tv_sunset.setGravity(Gravity.CENTER_VERTICAL); // 设置文字垂直居中

        tipTv.setText(resultsBean.getTips().getObserve().get_$0());
        // 获取今日天气情况
        WeatherBean.DataBean.ObserveBean todayDataBean = resultsBean.getObserve();
        String time = changeTime(todayDataBean.getUpdate_time());
        dateTv.setText("发布时间: " + time);
        windTv.setText("湿度 " + todayDataBean.getHumidity() + "%");
        tempRangeTv.setText("气压 " + todayDataBean.getPressure() + "hPa");

        // 切换图标
        String shortReport = todayDataBean.getWeather_short().trim();
        int resourceId;
        resourceId = getWeatherIcon(shortReport);
        weather_icon.setImageResource(resourceId);
        conditionTv.setText(shortReport);
        // 获取实时天气温度情况，需要处理字符串
        tempRangeTv.setText("气压  " + todayDataBean.getPressure() + "hPa");
        conditionTv.setText(todayDataBean.getWeather_short());
        MSG = "日期为" + time +","+ NowCityUtil.getNowCity() + " 的天气为" + "温度" + todayDataBean.getDegree() + "°C，" + "湿度为" + todayDataBean.getHumidity() + "%，" + "气压为" + todayDataBean.getPressure() + "hPa" + "天气" + todayDataBean.getWeather_short();
//        System.out.println(MSG);
        //        获取实时天气温度情况，需要处理字符串
        tempTv.setText(todayDataBean.getDegree() + "°C");

        /**
         * 获取未来天气情况，加载到layout当中
         */
        WeatherBean.DataBean.Forecast24hBean futureList = resultsBean.getForecast_24h();

        /**
         *  昨天天气情况
         */
        View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView idateTv = itemView.findViewById(R.id.item_center_tv_date);
        TextView iconTv = itemView.findViewById(R.id.item_center_tv_con);
        ImageView imageView = itemView.findViewById(R.id.frag_iv_weather_icon_forecast);
        TextView itemprangeTv = itemView.findViewById(R.id.item_center_tv_temp);
        //TextView wind = itemView.findViewById(R.id.item_center_tv_winddirection);
        // 获取对应的位置的天气情况
        String substringTime = futureList.get_$0().getTime().substring(5);
        idateTv.setText(substringTime + "   昨天");
        iconTv.setText(futureList.get_$0().getDay_weather());
        resourceId = getWeatherIcon(futureList.get_$0().getDay_weather());
        //System.out.println("1、当前id：" + resourceId);
        imageView.setImageResource(resourceId);
        //wind.setText(futureList.get_$2().getDay_wind_direction());
        itemprangeTv.setText(futureList.get_$0().getMin_degree() + " ~  " + futureList.get_$0().getMax_degree() + "°C");
        futureLayout.addView(itemView);

        /**
         * 今天天气情况
         */
        View itemView2 = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView idateTv2 = itemView2.findViewById(R.id.item_center_tv_date);
        TextView iconTv2 = itemView2.findViewById(R.id.item_center_tv_con);
        ImageView imageView2 = itemView2.findViewById(R.id.frag_iv_weather_icon_forecast);
        TextView itemprangeTv2 = itemView2.findViewById(R.id.item_center_tv_temp);
        //TextView wind2 = itemView2.findViewById(R.id.item_center_tv_winddirection);
        // 获取对应的位置的天气情况
        String substringTime2 = futureList.get_$1().getTime().substring(5);
        idateTv2.setText(substringTime2 + "   今天");
        iconTv2.setText(futureList.get_$1().getDay_weather());
        resourceId = getWeatherIcon(futureList.get_$1().getDay_weather());
        //System.out.println("2、当前id：" + resourceId);
        imageView2.setImageResource(resourceId);
        //wind2.setText(futureList.get_$3().getDay_wind_direction());
        itemprangeTv2.setText(futureList.get_$1().getMin_degree() + " ~  " + futureList.get_$1().getMax_degree() + "°C");
        futureLayout.addView(itemView2);
        /**
         * 明天 天气情况
         */
        View itemView3 = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView3.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView idateTv3 = itemView3.findViewById(R.id.item_center_tv_date);
        TextView iconTv3 = itemView3.findViewById(R.id.item_center_tv_con);
        ImageView imageView3 = itemView3.findViewById(R.id.frag_iv_weather_icon_forecast);
        TextView itemprangeTv3 = itemView3.findViewById(R.id.item_center_tv_temp);
        //TextView wind3 = itemView3.findViewById(R.id.item_center_tv_winddirection);
        // 获取对应的位置的天气情况
        String substringTime3 = futureList.get_$2().getTime().substring(5);
        idateTv3.setText(substringTime3 + "   明天");
        iconTv3.setText(futureList.get_$2().getDay_weather());
        resourceId = getWeatherIcon(futureList.get_$2().getDay_weather());
        //System.out.println("3、当前id：" + resourceId);

        imageView3.setImageResource(resourceId);
        //wind3.setText(futureList.get_$4().getDay_wind_direction());
        itemprangeTv3.setText(futureList.get_$2().getMin_degree() + " ~  " + futureList.get_$2().getMax_degree() + "°C");
        futureLayout.addView(itemView3);

        String weekday;
        Integer weekdayInt;
        /**
         * 后天 天气情况
         */
        View itemView4 = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView4.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView idateTv4 = itemView4.findViewById(R.id.item_center_tv_date);
        TextView iconTv4 = itemView4.findViewById(R.id.item_center_tv_con);
        ImageView imageView4 = itemView4.findViewById(R.id.frag_iv_weather_icon_forecast);
        TextView itemprangeTv4 = itemView4.findViewById(R.id.item_center_tv_temp);
        //TextView wind3 = itemView3.findViewById(R.id.item_center_tv_winddirection);
        // 获取对应的位置的天气情况
        String dayTime = futureList.get_$3().getTime();
        weekdayInt = TimeUtils.getWeekdayFromInput(dayTime);
        weekday = WeekdayConverter.convertToChinese(weekdayInt);
        idateTv4.setText(dayTime.substring(5) + "   " + weekday);
        iconTv4.setText(futureList.get_$3().getDay_weather());
        resourceId = getWeatherIcon(futureList.get_$3().getDay_weather());
        // System.out.println("4、当前id：" + resourceId);
        imageView4.setImageResource(resourceId);
        //wind3.setText(futureList.get_$4().getDay_wind_direction());
        itemprangeTv4.setText(futureList.get_$3().getMin_degree() + " ~  " + futureList.get_$3().getMax_degree() + "°C");
        futureLayout.addView(itemView4);


        /**
         * 大后天 天气情况
         */
        View itemView5 = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView5.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView idateTv5 = itemView5.findViewById(R.id.item_center_tv_date);
        TextView iconTv5 = itemView5.findViewById(R.id.item_center_tv_con);
        ImageView imageView5 = itemView5.findViewById(R.id.frag_iv_weather_icon_forecast);
        TextView itemprangeTv5 = itemView5.findViewById(R.id.item_center_tv_temp);
        //TextView wind3 = itemView3.findViewById(R.id.item_center_tv_winddirection);
        // 获取对应的位置的天气情况
        String dayTime2 = futureList.get_$4().getTime();
        weekdayInt = TimeUtils.getWeekdayFromInput(dayTime2);


        try {
            weekday = WeekdayConverter.convertToChinese(weekdayInt);
        }catch (Exception e){
            e.printStackTrace();
        }


        idateTv5.setText(dayTime2.substring(5) + "   " + weekday);

        iconTv5.setText(futureList.get_$4().getDay_weather());
        resourceId = getWeatherIcon(futureList.get_$4().getDay_weather());
        imageView5.setImageResource(resourceId);
        //System.out.println("5、当前id：" + resourceId);
        //wind3.setText(futureList.get_$4().getDay_wind_direction());
        itemprangeTv5.setText(futureList.get_$4().getMin_degree() + " ~  " + futureList.get_$4().getMax_degree() + "°C");
        futureLayout.addView(itemView5);

        /**
         * 大大后天 天气情况
         */
        View itemView6 = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView6.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView idateTv6 = itemView6.findViewById(R.id.item_center_tv_date);
        TextView iconTv6 = itemView6.findViewById(R.id.item_center_tv_con);
        ImageView imageView6 = itemView6.findViewById(R.id.frag_iv_weather_icon_forecast);
        TextView itemprangeTv6 = itemView6.findViewById(R.id.item_center_tv_temp);
        //TextView wind3 = itemView3.findViewById(R.id.item_center_tv_winddirection);
        // 获取对应的位置的天气情况
        String dayTime3 = futureList.get_$5().getTime();
        weekdayInt = TimeUtils.getWeekdayFromInput(dayTime3);
        weekday = WeekdayConverter.convertToChinese(weekdayInt);
        idateTv6.setText(dayTime3.substring(5) + "   " + weekday);
        iconTv6.setText(futureList.get_$5().getDay_weather());
        resourceId = getWeatherIcon(futureList.get_$5().getDay_weather());
        imageView6.setImageResource(resourceId);
        //System.out.println("5、当前id：" + resourceId);
        //wind3.setText(futureList.get_$4().getDay_wind_direction());
        itemprangeTv6.setText(futureList.get_$5().getMin_degree() + " ~  " + futureList.get_$5().getMax_degree() + "°C");
        futureLayout.addView(itemView6);

    }

    /**
     * 雨、雪、沙尘暴，雷阵雨、雨夹雪、多云
     *
     * @param shortReport
     * @return
     */
    private int getWeatherIcon(String shortReport) {

        if (shortReport == null || shortReport.length() == 0) {
            return 0;
        }
        String temp = "sunny";
        if (shortReport.contains("雨")) {
            temp = "rainy";
        }
        if (shortReport.contains("雪")) {
            temp = "snowy";
        }
        if (shortReport.contains("沙")) {
            temp = "sandstorm";
        }
        if (shortReport.contains("雷阵雨")) {
            temp = "thunderstorm";
        }
        if (shortReport.contains("雨夹雪")) {
            temp = "sleet";
        }
        if (shortReport.contains("云") || shortReport.contains("阴")) {
            temp = "cloudy";
        }
        if (shortReport.contains("雾")) {
            temp = "foggy";
        }
        // 获取图片资源ID
        int tempId;
        tempId = getActivity().getResources().getIdentifier(temp, "mipmap", getActivity().getPackageName());
        return tempId;
    }

    private String changeTime(String update_time) throws ParseException {
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyyMMddHHmm");
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String sfstr = "";
        sfstr = sf2.format(sf1.parse(update_time));
        return sfstr;
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        // 数据库当中查找上一次信息显示在Fragment当中
        String s = DBManager.queryInfoByCity(city);
        if (!TextUtils.isEmpty(s)) {
            try {
                parseShowData(s);
            } catch (ParseException | NoSuchMethodException | IllegalAccessException |
                     InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private void initView(View view) {
        // 用于初始化控件操作
        tipTv = view.findViewById(R.id.frag_tv_tips);
        tempTv = view.findViewById(R.id.frag_tv_currenttemp);

        frag_tv_aqi_name = view.findViewById(R.id.frag_tv_aqi_name);
        frag_tv_PM2_5 = view.findViewById(R.id.frag_tv_PM2_5);
        frag_tv_sunrise = view.findViewById(R.id.frag_tv_sunrise);
        frag_tv_sunset = view.findViewById(R.id.frag_tv_sunset);

        conditionTv = view.findViewById(R.id.frag_tv_condition);
        windTv = view.findViewById(R.id.frag_tv_wind);
        tempRangeTv = view.findViewById(R.id.frag_tv_temprange);
        dateTv = view.findViewById(R.id.frag_tv_date);
        clothIndexTv = view.findViewById(R.id.frag_index_tv_dress);
        carIndexTv = view.findViewById(R.id.frag_index_tv_washcar);
        coldIndexTv = view.findViewById(R.id.frag_index_tv_cold);
        sportIndexTv = view.findViewById(R.id.frag_index_tv_sport);
        raysIndexTv = view.findViewById(R.id.frag_index_tv_rays);
        // 天气图标
        weather_icon = view.findViewById(R.id.frag_iv_weather_icon);
        futureLayout = view.findViewById(R.id.frag_center_layout);
        outLayout = view.findViewById(R.id.out_layout);
        umbrellaTv = view.findViewById(R.id.frag_index_tv_umbrella);
        // 设置点击事件的监听
        clothIndexTv.setOnClickListener(this);
        carIndexTv.setOnClickListener(this);
        coldIndexTv.setOnClickListener(this);
        sportIndexTv.setOnClickListener(this);
        raysIndexTv.setOnClickListener(this);
        umbrellaTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        switch (v.getId()) {
            case R.id.frag_index_tv_dress:
                builder.setTitle("穿衣指数");
                WeatherBean.DataBean.IndexBean.ClothesBean cloth = index.getClothes();
                String msg = cloth.getInfo() + "\n" + cloth.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_index_tv_washcar:
                builder.setTitle("洗车指数");
                WeatherBean.DataBean.IndexBean.CarwashBean car = index.getCarwash();
                msg = car.getInfo() + "\n" + car.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_index_tv_cold:
                builder.setTitle("感冒指数");
                WeatherBean.DataBean.IndexBean.ColdBean cold = index.getCold();
                msg = cold.getInfo() + "\n" + cold.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_index_tv_sport:
                builder.setTitle("运动指数");
                WeatherBean.DataBean.IndexBean.SportsBean sport = index.getSports();
                msg = sport.getInfo() + "\n" + sport.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_index_tv_rays:
                builder.setTitle("紫外线指数");
                WeatherBean.DataBean.IndexBean.UltravioletBean ultraviolet = index.getUltraviolet();
                msg = ultraviolet.getInfo() + "\n" + ultraviolet.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_index_tv_umbrella:
                builder.setTitle("雨伞指数");
                WeatherBean.DataBean.IndexBean.UmbrellaBean umbrella = index.getUmbrella();
                msg = umbrella.getInfo() + "\n" + umbrella.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
        }
        builder.create().show();
    }


    // 交换壁纸的函数
    public void exchangeBg() {
        pref = getActivity().getSharedPreferences("bg_pref", MODE_PRIVATE);
        bgNum = pref.getInt("bg", 2);
        switch (bgNum) {
            case 0:
                outLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outLayout.setBackgroundResource(R.mipmap.bg3);
                break;
            case 99:
                try {
                    //从缓存取出图片
                    Drawable photo1 = SpUtils.getDrawableByKey(getContext(), "photo");
                    outLayout.setBackground(photo1);

                    break;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "加载壁纸失败，源文件可能已经被删除，挪动。", Toast.LENGTH_SHORT).show();
                    outLayout.setBackgroundResource(R.mipmap.bg2);
                    break;
                }
        }
    }
}